<template>
  <div class="app-container" v-loading="loading">
    <el-form :model="formData" :rules="rules" ref="validateForm" label-width="140px">
      <el-form-item label="标题" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>

      <el-form-item label="网址" prop="url">
        <el-input v-model="formData.url"></el-input>
      </el-form-item>

      <!-- <el-form-item label="图片" prop="pic">
        <el-upload :action="actionUrl" list-type="picture-card" :auto-upload="true" :file-list="uploadFile.list"
          name="upload" drag :limit="uploadFile.limit" :on-success="onUploadChange" :on-exceed="onUploadExceed"
          :headers="uploadHeaders">
          <i slot="default" class="el-icon-plus"></i>
        </el-upload>
      </el-form-item> -->

      <el-form-item label="图片" prop="pic">
        <upload :limit="3" v-model="formData.pic" ref="upload" :multiple="false"></upload>

      </el-form-item>

      <el-form-item label="简介" prop="intro">
        <el-input v-model="formData.intro"></el-input>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-switch v-model="formData.status"></el-switch>
        {{ formData.status ? '开启' : '停用' }}
      </el-form-item>

      <el-form-item>
        <el-button type="primary" id="editor" @click="submitForm('validateForm')">提交</el-button>
        <el-button @click="resetForm('validateForm')">重置</el-button>
      </el-form-item>


    </el-form>
  </div>
</template>
<script>
import { getDetail, create, update } from '@/api/banner'
import { getOssData, sendOssData } from '@/api/common';
import { baseHost } from '@/utils'
import { getToken } from '@/utils/auth'
import Upload from "@/components/Global/Upload"
const token = getToken()
const Authorization = `Bearer ${token}`

const routePath = '/banner/'

export default {
  name: 'BannerCreateUpdate',
  components: { Upload },
  filters: {},
  props: {
    type: {
      type: String,
      default: function () {
        return 'create'
      },
    },
  },
  data() {
    return {
      loading: false,
      // query 参数
      querys: {
        id: '',
      },

      formData: {
        id: '',
        name: '',
        url: '',
        pic: '',
        intro: '',
        status: true,
      },
      rules: {
        name: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          {
            min: 1,
            max: 40,
            message: '长度在 1 到 40 个字符',
            trigger: 'blur',
          },
        ],
        pic: [
          {
            required: true,
            length: 1,
            message: '请上传图片',
            trigger: 'change',
          },
        ],
      },

      categoryList: [],

      // 文件上传
      uploadHeaders: {
        Authorization,
      },
      uploadFile: {
        list: [],
        limit: 1,
      },
    }
  },
  watch: {},
  created() {
    this.getQuery()
  },
  computed: {
    actionUrl() {
      if (process.env.NODE_ENV == 'development') {
        return '/api/upload'
      }
      else {
        return `${process.env.VUE_APP_BASE_HOST}api/upload`
      }
    }
  },
  methods: {
    async handleUpload(file, cb) {
      // 生成文件名，作为 key 使用
      const generateFileName = (ossData, file) => {
        const suffix = file.name.slice(file.name.lastIndexOf('.'));
        const filename = Date.now() + suffix;
        return ossData.dir + filename;
      }
      // const file = this.$refs.fileRef.files[0]
      const ossData = await getOssData()
      const key = generateFileName(ossData, file)
      const formdata = new FormData()
      // 注意参数的顺序，key 必须是第一位，表示OSS存储文件的路径
      formdata.append('key', key)
      formdata.append('OSSAccessKeyId', ossData.accessId)
      formdata.append('policy', ossData.policy)
      formdata.append('signature', ossData.signature)
      // 文件上传成功默认返回 204 状态码，可根据需要修改为 200
      formdata.append('success_action_status', '200')
      // file 必须放在最后一位
      formdata.append('file', file)
      const res = await sendOssData(ossData.host, formdata);
      if (res.status === 200) {
        cb(ossData.host + '/' + key)
        // this.formData.pic = ossData.host + '/' + key
      }
    },
    uploadFn(params) {
      this.handleUpload(params.file, (res) => {
        this.formData.pic = res
      })
      console.log('[ params ] >', params)
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false
        }

        this.loading = true

        if (this.type === 'update') {
          this.putUpdate()
        } else {
          this.postCreate()
        }
      })
    },

    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    // 获取  query 参数
    getQuery() {
      const querys = this.$route.query || {}
      this.querys = querys

      if (this.type === 'update') {
        if (!querys.id) {
          this.$router.push('list')
          return
        }
        this.getDetail()
      }
    },

    // 文件上传添加
    onUploadChange(res) {
      console.log('[ res ] >', res)
      this.formData.pic = res.path
      // this.formData.pic = res.url
    },

    // 超出文件
    onUploadExceed() {
      this.$message({
        message: '抱歉，只能上传一张图片',
        type: 'error',
      })
    },

    // 添加
    postCreate() {
      create(this.formData).then(() => {
        this.loading = false

        this.$message({
          message: '恭喜，操作成功',
          type: 'success',
          duration: 1000,
        })

        setTimeout(() => {
          this.$router.push(`/home${routePath}list`)
        }, 1000)
      })
    },

    // 更新
    putUpdate() {
      update(this.formData).then(() => {
        this.loading = false

        this.$message({
          message: '恭喜，操作成功',
          type: 'success',
          duration: 1000,
        })

        setTimeout(() => {
          this.$router.push(`/home${routePath}list`)
        }, 1000)
      })
    },

    // 详情
    getDetail() {
      this.loading = true

      getDetail(this.querys.id).then((res) => {
        this.loading = false

        const { pic } = res
        this.uploadFile.list.push({
          name: pic,
          url: baseHost + pic.replace('public/', ''),
        })

        this.formData = res
      })
    },
  },
}
</script>
